# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://www.1madai.cn/olt/org/orgH5PayMent'
_QUERY_GATEWAY = 'http://www.1madai.cn/olt/qrt/orgConfirmPay'

APP_CONF = {
    'O00000000002218': {
        'API_KEY': '5BE453B5C0FA44708C9A73A487FE7F73'
    }
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s' % parameter[k]
    s += '%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info('origin_str:%s, generate_sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    s = '{}{}{}{}{}{}'.format(params['payresult'], params['outradeno'], params['referenceNo'],
                              params['transAmount'], params['merchantNo'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("madaipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    service = info['service']  # wechat or alipay
    pay_type = '10000003' if service == 'alipay' else '10000001'
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '1.0'),
        ('merchantNo', app_id),
        ('paytype', '10000001'),
        ('outTradeNo', str(pay.id)),
        ('amt', str(pay_amount)),
        ('retUrl', '{}/pay/api/{}/mdpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('pageUrl', '{}/pay/api/{}/mdpay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('callType', 'url'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("madaipay create charge data: %s %s",
                 response.status_code, response.text)
    res_obj = json.loads(response.text)
    charge_resp.update({
        'charge_info': res_obj['payUrl'],
    })
    return charge_resp


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("madaipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['outradeno']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('madaipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['payresult']
    trade_no = data['referenceNo']
    total_fee = float(data['transAmount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status.upper() == 'SUCCESS':
        _LOGGER.info('madaipay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('merchantNo', app_id),
        ('outTradeNo', pay_order.id),
    ))
    p_dict['sign'] = generate_sign(p_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=p_dict, headers=headers, timeout=3)
    _LOGGER.info("madaipay create charge data: %s %s",
                 response.status_code, response.text)
    if response.status_code == 200:
        # response text is a pure html text
        _LOGGER.info('madaipay query:%s', response.text)
        data = json.loads(response.text)

        mch_id = pay_order.mch_id
        trade_status = data['payStatus']
        trade_no = data['referenceNo']
        total_fee = float(data['transAmount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 'SUCCESS':
            _LOGGER.info('madaipay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
